﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Xml.Linq;
using DevCow.Api.Meetup.Events;

namespace DevCow.Api.Meetup
{
    public class MeetupApiClient
    {
        public string ApiKey { get; set; }

        public MeetupApiClient(string apiKey)
        {
            ApiKey = apiKey;
        }

        private const string host = "http://api.meetup.com/{0}.{1}/{2}&key={3}";
        private string CallMeetupApi(string Method, string CallFormat, string MethodParameters)
        {
            string url = String.Format(host, Method, CallFormat, MethodParameters, ApiKey);
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

            if (null == request)
            {
                throw new ApplicationException("Could not make HttpWebRequest");
            }
            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }

        #region Meetup Methods
        public void Groups()
        {
        }

        public MeetupEvents Events(MeetupEventRequest searchCriteria)
        {
            if (searchCriteria == null)
            {
                throw new ArgumentNullException("Search Criteria is required.");
            }

            string parameters = searchCriteria.GetRequestParameters();

            if(parameters == null)
            {
                throw new ArgumentNullException("Search Criteria is required.");
            }

            MeetupEvents events = null;
            //"/events.xml/?group_id=444077&order=time&key=*****""
            //string results = CallMeetupApi("events", "xml", parameters);
            //XDocument xml = XDocument.Parse(results);
            XDocument xml = XDocument.Parse(File.ReadAllText(@"C:\temp\testxml.xml"));
            try
            {
                
                XElement items = xml.Element("results").Element("items");
                if (items != null)
                {
                    events = new MeetupEvents();
                    System.Xml.Serialization.XmlSerializer x =
                        new System.Xml.Serialization.XmlSerializer(events.GetType());
                    events = (MeetupEvents) x.Deserialize(items.CreateReader());
                }
            }
            catch (Exception ex)
            {
                //TODO: Write to a central logging
                Debug.WriteLine(ex.Message);
            }

            return events;
        }
        public void Members()
        {
        }
        public void Rsvps()
        {
        }
        public void Topics()
        {
        }
        public void Photos()
        {
        }
        public void Cities()
        {
        }
        #endregion
    }

   
}
